package com.pms.service.impl;

import java.text.ParseException;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.pms.dao.JobConfigMapper;
import com.pms.domain.JobConfig;
import com.pms.service.SchedulerService;
import com.pms.task.FTPJob;

@Component
public class SchedulerServiceImpl implements SchedulerService {
	
	public static Logger logger = Logger.getLogger(SchedulerServiceImpl.class);

	@Autowired
	private JobConfigMapper jobConfigMapper;

	@Autowired
	SchedulerFactoryBean schedulerFactoryBean;

	@Autowired
	FTPJob fTPJob;

	@Scheduled(cron = "0 */1 * * * ?")
	@Override
	public void run() {

		logger.info("周期配置调度任务...");
		try {
			reScheduleJob();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void reScheduleJob() throws Exception, ParseException {
		// 通过查询数据库里计划任务来配置计划任务

		List<JobConfig> list = jobConfigMapper.selectJobConfigByGroup("ftp");
		if (list != null && list.size() > 0) {
			for (JobConfig cfg : list) {
				configQuatrz(cfg);
			}
		}
	}

	public boolean configQuatrz(JobConfig cfg) {
		boolean result = false;
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		try {

			// TriggerKey triggerKey = TriggerKey.triggerKey(cfg.getJobname(),
			// Scheduler.DEFAULT_GROUP);
			TriggerKey triggerKey = TriggerKey.triggerKey(cfg.getJobname(), cfg.getJobgroup());
			// 获取触发器trigger
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

			if (null == trigger) {// 不存在任务

				// 创建任务
				// JobDetail jobDetail = JobBuilder.newJob(fTPJob.class)
				// .withIdentity(tbcq.getJobdetailname(),
				// Scheduler.DEFAULT_GROUP)
				// .build();

				JobDetail jobDetail = JobBuilder.newJob(fTPJob.getClass())
						.withIdentity(cfg.getJobname(), cfg.getJobgroup()).build();

				jobDetail.getJobDataMap().put("jobConfig", cfg);
				
				System.out.println("cron:" + cfg.getCronexpression());
				// 表达式调度构建器
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cfg.getCronexpression());

				// 按新的cronExpression表达式构建一个新的trigger
				trigger = TriggerBuilder.newTrigger().withIdentity(cfg.getJobname(), cfg.getJobgroup())
						.withSchedule(scheduleBuilder).build();

				scheduler.scheduleJob(jobDetail, trigger);

			} else {// 存在任务
					// Trigger已存在，那么更新相应的定时设置
					// 表达式调度构建器
				//CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cfg.getCronexpression());

				// 按新的cronExpression表达式重新构建trigger
				//trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

				// 按新的trigger重新设置job执行
				//scheduler.rescheduleJob(triggerKey, trigger);

			}

		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}

		return result;
	}

}
